package com.xingbg.projectimpl.config.customimpl;

import com.xingbg.projectimpl.config.EnableCustomService;
import com.xingbg.projectimpl.config.bean.LiskovBeanProessor;
import lombok.SneakyThrows;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;

import java.util.Map;

public class LiskovBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {
    @SneakyThrows
    @Override
    public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry beanDefinitionRegistry) {
        Map<String, Object> annotationAttributes = annotationMetadata.getAnnotationAttributes(EnableCustomService.class.getName(), true);
        String[] basePackages =  (String[]) annotationAttributes.get("basePackages");
        if (basePackages==null || basePackages.length==0) {
            String basePackage = Class.forName(annotationMetadata.getClassName()).getPackage().getName();
            basePackages = new String[]{basePackage};
        }
        BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.rootBeanDefinition(LiskovBeanProessor.class.getName());
        beanDefinitionBuilder.addConstructorArgValue(basePackages);
        AbstractBeanDefinition beanDefinition = beanDefinitionBuilder.getBeanDefinition();

        beanDefinitionRegistry.registerBeanDefinition(this.getBeanName(basePackages),beanDefinition);

    }

    private String getBeanName(String[] basePackages) {
        return "liskov-"+String.join("-",basePackages);
    }
}
